/***********************************************************************************************************************
*                                                                                                                      *
* SPLASH build system v0.1                                                                                             *
*                                                                                                                      *
* Copyright (c) 2013 Andrew D. Zonenberg                                                                               *
* All rights reserved.                                                                                                 *
*                                                                                                                      *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the     *
* following conditions are met:                                                                                        *
*                                                                                                                      *
*    * Redistributions of source code must retain the above copyright notice, this list of conditions, and the         *
*      following disclaimer.                                                                                           *
*                                                                                                                      *
*    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       *
*      following disclaimer in the documentation and/or other materials provided with the distribution.                *
*                                                                                                                      *
*    * Neither the name of the author nor the names of any contributors may be used to endorse or promote products     *
*      derived from this software without specific prior written permission.                                           *
*                                                                                                                      *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES        *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR       *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE       *
* POSSIBILITY OF SUCH DAMAGE.                                                                                          *
*                                                                                                                      *
***********************************************************************************************************************/

#include "splashcore.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Constgen file parsing

ConstgenSourceNode::ConstgenSourceNode(BuildGraph* graph, std::string srcfile)
	: CodeGenScriptNode(graph, srcfile)
{
	FILE* fp = fopen(srcfile.c_str(), "r");
	if(!fp)
		FatalError("Could not open constgen file %s\n", srcfile.c_str());
		
	char line[1024];
	char name[256];
	char value[256];
	while(NULL != fgets(line, sizeof(line), fp))
	{
		//Remove C++ comments and leading whitespace
		char* pline = line;
		char* pcom = strstr(pline, "//");
		if(pcom != NULL)
			*pcom = '\0';
		while(isspace(*pline))
			pline ++;
			
		//Skip blank lines
		if(strlen(pline) == 0)
			continue;
		
		//Parse
		if(2 != sscanf(line, "%255s %255s", name, value))
			continue;
			
		//Figure out number format
		//Default with is 32 bits unless otherwise specified
		char numval[255];
		unsigned int width = 32;
		unsigned int ivalue = 0;
		char base = 'd';
		if(strstr(value, "'") != NULL)
		{
			if(3 != sscanf(value, "%d'%c%255s", &width, &base, numval))
				FatalError("Syntax error: Can't parse constgen line %s\n", line);
			
			switch(base)
			{
			case 'b':
				ivalue = strtoul(numval, NULL, 2);
				break;
			case 'o':
				ivalue = strtoul(numval, NULL, 8);
				break;
			case 'd':
				ivalue = strtoul(numval, NULL, 10);
				break;
			case 'h':
				ivalue = strtoul(numval, NULL, 16);
				break;
			default:
				FatalError("Unrecognized base '%c' in '%s'\n", base, line);
			}
		}
		else
			ivalue = strtoul(value, NULL, 0);
		
		m_constants[name] = std::pair<unsigned int, unsigned int>(width, ivalue);
	}
		
	fclose(fp);
}

ConstgenSourceNode::~ConstgenSourceNode()
{
	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

CppConstgenNode::CppConstgenNode(BuildGraph* graph, ConstgenSourceNode* src, string fname)
	: CppGeneratedSourceNode(graph, fname, "generic")
	, m_srcfile(src)
{
	m_dependencies.push_back(src);
}

CppConstgenNode::~CppConstgenNode()
{
	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors

string CppConstgenNode::GetOutputPath()
{
	return GetBinaryPath();
}

string CppConstgenNode::GetDescription()
{
	char desc[1024];
	snprintf(desc, sizeof(desc), "C++ constant table %s", m_fname.c_str());
	return string(desc);
}

string CppConstgenNode::GetBinaryPath()
{
	return m_graph->GetOutDir() + "/generic/include/" + m_fname;
}

string CppConstgenNode::GetHash()
{
	return sha256(m_srcfile->GetHashCached() + sha256(m_fname) + sha256("cpp"));
}

void CppConstgenNode::Update(Cluster* cluster)
{
	//Print the heading
	DebugPrintfHeading(3, "Generating constant include file %s\n", m_fname.c_str());
	
	//Rebuild our dependencies (in case any source files were auto-generated, etc)
	vector<ClusterJob*> deps;
	for(size_t i=0; i<m_dependencies.size(); i++)
	{
		BuildGraphNode* node = m_dependencies[i];
		node->UpdateCached(cluster);
		if(node->GetBuildJob() != NULL)
			deps.push_back(node->GetBuildJob());
	}
	
	//Should not be any cluster jobs - if there are, fail
	if(deps.size() != 0)
		FatalError("CppConstgenNode does not expect cluster jobs");
		
	//Set up output file
	string fname = GetBinaryPath();
	char cmd[256];
	snprintf(cmd, sizeof(cmd), "mkdir -p %s", GetDirOfFile(fname).c_str());
	system(cmd);
	FILE* fp = fopen(fname.c_str(), "w");
	
	//Include guards
	string srcfile = m_srcfile->GetOutputPath();
	string guard = string("CONSTGEN_INCLUDE_GUARD_") + GetBasenameOfFileWithoutExt(srcfile);
	
	//File header
	fprintf(fp, "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n");
	fprintf(fp, "// Generated automatically by CppConstgenNode from %s\n", srcfile.c_str());
	fprintf(fp, "// DO NOT EDIT\n");
	fprintf(fp, "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n");
	fprintf(fp, "\n");
	fprintf(fp, "#ifndef %s\n", guard.c_str());
	fprintf(fp, "#define %s\n", guard.c_str());
	fprintf(fp, "\n");
	
	//File body
	char tline[128];
	for(auto x : m_srcfile->m_constants)
	{
		snprintf(tline, sizeof(tline), "#define %-20s 0x%x", x.first.c_str(), x.second.second);
		fprintf(fp, "%-50s /* %d bits wide */\n", tline, x.second.first);
	}
	
	//File footer	
	fprintf(fp, "\n");
	fprintf(fp, "#endif //#ifndef %s\n", guard.c_str());
	fclose(fp);
}

void CppConstgenNode::UpdateDependencies()
{
	//Nothing to do
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory method

CppConstgenNode* CppConstgenNode::CreateCppConstgenNode(BuildGraph* graph, string script)
{
	//See if the source file has been used. If not, create a node for it.
	script = CanonicalizePath(script);
	ConstgenSourceNode* srcnode = dynamic_cast<ConstgenSourceNode*>(graph->GetNodeForPath(script, "generic"));
	if(srcnode == NULL)
	{
		srcnode = new ConstgenSourceNode(graph, script);
		graph->AddNodeWithPath(srcnode, script, "generic");
	}
	
	//Generate output file name
	string outfname = GetBasenameOfFileWithoutExt(script) + "_constants.h";
	
	//Create the constgen node itself
	CppConstgenNode* node = new CppConstgenNode(graph, srcnode, outfname);
	graph->AddNodeWithPath(node, node->GetOutputPath(), "generic");

	//Done
	return node;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

VerilogConstgenNode::VerilogConstgenNode(BuildGraph* graph, ConstgenSourceNode* src, string fname)
	: VerilogGeneratedSourceNode(graph, fname)
	, m_srcfile(src)
{
	m_dependencies.push_back(src);
}

VerilogConstgenNode::~VerilogConstgenNode()
{
	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors

string VerilogConstgenNode::GetOutputPath()
{
	return GetBinaryPath();
}

string VerilogConstgenNode::GetDescription()
{
	char desc[1024];
	snprintf(desc, sizeof(desc), "Verilog constant table %s", m_fname.c_str());
	return string(desc);
}

string VerilogConstgenNode::GetBinaryPath()
{
	return m_graph->GetOutDir() + "/generic/include/" + m_fname;
}

string VerilogConstgenNode::GetHash()
{
	return sha256(m_srcfile->GetHashCached() + sha256(m_fname) + sha256("verilog"));
}

void VerilogConstgenNode::Update(Cluster* cluster)
{
	//Print the heading
	DebugPrintfHeading(3, "Generating constant include file %s\n", m_fname.c_str());
	
	//Rebuild our dependencies (in case any source files were auto-generated, etc)
	vector<ClusterJob*> deps;
	for(size_t i=0; i<m_dependencies.size(); i++)
	{
		BuildGraphNode* node = m_dependencies[i];
		node->UpdateCached(cluster);
		if(node->GetBuildJob() != NULL)
			deps.push_back(node->GetBuildJob());
	}
	
	//Should not be any cluster jobs - if there are, fail
	if(deps.size() != 0)
		FatalError("VerilogConstgenNode does not expect cluster jobs");
		
	//Set up output file
	string fname = GetBinaryPath();
	char cmd[256];
	snprintf(cmd, sizeof(cmd), "mkdir -p %s", GetDirOfFile(fname).c_str());
	system(cmd);
	FILE* fp = fopen(fname.c_str(), "w");
	
	//File header
	fprintf(fp, "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n");
	fprintf(fp, "// Generated automatically by VerilogConstgenNode from %s\n", m_srcfile->GetOutputPath().c_str());
	fprintf(fp, "// DO NOT EDIT\n");
	fprintf(fp, "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n");
	fprintf(fp, "\n");
	
	//File body
	for(auto x : m_srcfile->m_constants)
		fprintf(fp, "localparam %-20s = %d'h%x;\n", x.first.c_str(), x.second.first, x.second.second);
	
	//File footer	
	fprintf(fp, "\n");
	fclose(fp);
}

void VerilogConstgenNode::UpdateDependencies()
{
	//Nothing to do
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory method

VerilogConstgenNode* VerilogConstgenNode::CreateVerilogConstgenNode(BuildGraph* graph, string script)
{
	//See if the source file has been used. If not, create a node for it.
	script = CanonicalizePath(script);
	ConstgenSourceNode* srcnode = dynamic_cast<ConstgenSourceNode*>(graph->GetNodeForPath(script, "generic"));
	if(srcnode == NULL)
	{
		srcnode = new ConstgenSourceNode(graph, script);
		graph->AddNodeWithPath(srcnode, script, "generic");
	}
	
	//Generate output file name
	string outfname = GetBasenameOfFileWithoutExt(script) + "_constants.v";
	
	//Create the constgen node itself
	VerilogConstgenNode* node = new VerilogConstgenNode(graph, srcnode, outfname);
	graph->AddNodeWithPath(node, node->GetOutputPath(), "generic");

	//Done
	return node;
}
